<?php
namespace app\store\controller\setting;

use app\store\controller\Controller;
use think\Request;

/**
 * 帮助文档
 * Class Article
 * @package app\store\controller\setting
 */
class Article extends Controller
{
    /**
     * 列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $request = Request::instance();
        $list = db("article")->order(['article_id' => 'desc'])->paginate(15, false, ['query' => $request->request()])->each(function($item, $key){
            $item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
            return $item;
        });
        return $this->fetch('index', compact('list'));
    }
    
    /**
     * 新增
     */
    public function add() {
        return $this->post();
    }
    
    /**
     * 修改
     */
    public function edit() {
        $id = $this->request->param('id/d' , 0);
        if( !$data = db("article")->where(['article_id' => $id])->find()){
            $this->error("数据不存在");
        }
        return $this->post($data);
    }
    
    /**
     * 删除
     */
    public function delete() {
        $request = Request::instance();
        $id = $request->post('id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('article')->where(['article_id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    private function post($save_data = array()) {
        if ($this->request->isAjax()) {
            $data = $this->postData('article');
            $article_id = $this->request->post('id/d' , 0);
            if( $article_id > 0 ) {
                $res = db("article")->where(['article_id' => $article_id])->update($data);
                if( $res ) {
                    $this->success('帮助文档修改成功');
                } else {
                    $this->error('修改失败');
                }
            }else {
                $data['create_time'] = time();
                $res = db("article")->insert($data);
                if( $res ) {
                    $this->success('帮助文档添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
        }
        return $this->fetch('',compact('save_data'));
    }
}
